package com.chinackts.common.filestorage;

import com.chinackts.common.exception.ApplicationException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.zhoujianhui.filestorage.model.FileContent;
import org.zhoujianhui.filestorage.model.FileMetaInfo;
import org.zhoujianhui.filestorage.service.FileStorageService;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Lianhong
 * @since 2021/11/29、
 * 文件存储服务
 */
@Component
public class EPortFileStorageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EPortFileStorageService.class);

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 存储文件
     *
     * @param module   存储模块
     * @param fileName 文件名称
     */
    public FileMetaInfo store(StorageModule module, String fileName, byte[] bytes) throws IOException {
//        /*DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.ALL_VALUE, true, fileName);
//        IOUtils.copy(in, fileItem.getOutputStream());
//        return fi*/leStorageService.uploadFile(module.toString(), new CommonsMultipartFile(fileItem));
        InputStream in = null;
        OutputStream out = null;
        try {
            DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.ALL_VALUE, true, fileName);
            in = new ByteArrayInputStream(bytes);
            out = fileItem.getOutputStream();
            IOUtils.copy(in, out);
            return fileStorageService.uploadFile(module.toString(), new CommonsMultipartFile(fileItem));
        } catch (Exception e) {
            LOGGER.error("文件存储失败", e);
            throw new ApplicationException("文件存储失败");
        } finally {
            if (out != null) out.flush();
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 加载文件
     *
     * @param module         存储模块
     * @param storedFileName 已存储文件名称
     */
    public FileContent load(StorageModule module, String storedFileName) {
        return fileStorageService.getFile(module.toString(), storedFileName);
    }

    /**
     * 删除文静
     *
     * @param module         存储模块
     * @param storedFileName 已存储文件名称
     */
    public void delete(StorageModule module, String storedFileName) {
        fileStorageService.deleteFile(module.toString(), storedFileName);
    }
}
